#include "ring_node.h"

#define MAX_STRING 32

void ring_node(int parent, int node_id){

  int32_t parent_pid = (int32_t)parent;
  int32_t next_node_pid;
  int message_number = 1;

  /* get next ring nodes id from parent */
  message m;
  recevoir_destinataire(parent_pid, &m);
  next_node_pid = (int32_t)m.data.int_data;
  //ecrire("parent_id is ");
  //ecrire(itoa(parent_pid, s, 10));
  //ecrire("\n");
  //ecrire("next_node_pid is ");
  //ecrire(itoa(next_node_pid, s, 10));
  //ecrire("\n");

  while (message_number <= NUMBER_OF_MESSAGES) {
    /* if we are the "last" node in the ring (the next node has
     * a smaller pid than we) we control the messages. That means
     * we create the first ones and are the last to receive. */
    /* If messages were already sent, we have to receive */
    if (obtenir_pid() > next_node_pid) {
      message m;
      recevoir_premier(&m);
      if (message_number == 1) {
        ecrire("Will start sending messages.\n");
      } else {
        ecrire("Message went through ring: \"");
        ecrire(m.data.str_data);
        ecrire("\"\n");
      }
      char s[MAX_STRING];
      char i[4];
      strncpy(s, "Message number ", MAX_STRING-1);
      itoa(message_number, i, 4);
      strncat(s, itoa(message_number, i, 4), 32);
      ecrire("Inserting message into ring: ");
      ecrire(s);
      ecrire("\n");
      retarder(obtenir_pid(), 3000);
      envoyer_chaine(next_node_pid, s, 9);
      message_number++;
      /* We are not the controlling node, just receive and send forth */
    } else {
      message m;
      char s[10];
      char text[MAX_STRING];
      //ecrire("Will receive shortly...\n");
      recevoir_premier(&m);
      strncpy(text, m.data.str_data, 32);
      ecrire("Node number ");
      ecrire(itoa(node_id, s, 10));
      ecrire(" received: \"");
      ecrire(m.data.str_data);
      ecrire("\"\n");
      retarder(obtenir_pid(), 3000);
      envoyer_chaine(next_node_pid, m.data.str_data, 9);
      message_number++;
    }
    //ecrire("Sleeping for some time...\n");
    //retarder(obtenir_pid(), 1000);
    //char o[32], f[4];
    //strncpy(o, "\ncount is ", 32);
    //strncat(o, itoa(message_number, f, 4), 32);
    //strncat(o, "\n", 32);
    //ecrire(o);
  }
  /* get the last message and finish up */
  if (obtenir_pid() > next_node_pid) {
    message m;
    recevoir_premier(&m);
    ecrire("Message went through ring: \"");
    ecrire(m.data.str_data);
    ecrire("\"\n");
    ecrire("All messages send through ring...\n");
    /* to get any messages that are over */
    //recevoir_premier(&m);
  }
  quitter(0);
}
